package cn.hiapi.shopkeeper.service;

import cn.hiapi.interfaces.DispatchContext;
import cn.hiapi.interfaces.config.IConfigService;
import cn.hiapi.interfaces.finance.IBankCodeListService;
import cn.hiapi.interfaces.finance.model.BankCode;
import cn.hiapi.shopkeeper.consts.AppConst;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author AdinZ
 * @date 2023/2/17 22:21
 */
@Service
public class BankCodeService implements IBankCodeListService {

    private final DispatchContext dispatchContext;

    public BankCodeService(DispatchContext dispatchContext) {
        this.dispatchContext = dispatchContext;
    }

    private List<BankCode> list;


    @Override
    public List<BankCode> findAll() {
        if (list == null || list.isEmpty()) {
            JSONObject config = this.dispatchContext.getServiceOne(IConfigService.class).getConfig(0, AppConst.CONFIG_BANK_CODE_LIST);
            list = config.getJSONArray("list").toJavaList(BankCode.class);
        }
        return list;
    }

    @Override
    public BankCode findByCode(String code) {
        List<BankCode> list = this.findAll();
        Optional<BankCode> optional = list.stream().filter(e -> StringUtils.equals(e.getCode(), code)).findFirst();
        return optional.isPresent() ? optional.get() : null;
    }

    @Override
    public BankCode findByName(String name) {
        List<BankCode> list = this.findAll();
        Optional<BankCode> optional = list.stream().filter(e -> StringUtils.equals(e.getName(), name)).findFirst();
        return optional.isPresent() ? optional.get() : null;
    }
}
